package com.cainiao.service.deptserviceimpl;

import com.cainiao.exception.BuinessException;
import com.cainiao.mapper.ClazzMapper;
import com.cainiao.mapper.StudentMapper;
import com.cainiao.pojo.Clazz;
import com.cainiao.pojo.ClazzQueryParam;
import com.cainiao.pojo.PageBean;
import com.cainiao.service.ClazzService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service

public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;


    @Autowired
    private StudentMapper studentMapper;
    @Override
    public PageBean page(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        List<Clazz> clazzList = clazzMapper.page(clazzQueryParam);
        clazzList.forEach(clazz -> {
            LocalDate beginDate = clazz.getBeginDate();
            LocalDate endDate = clazz.getEndDate();
            LocalDate now = LocalDate.now();
            if (now.isAfter(beginDate)&& now.isBefore(endDate)) {
                clazz.setStatus("在读");
            } else if (now.isAfter(endDate)) {
                clazz.setStatus("已结束");
            } else {
                clazz.setStatus("未开班");
            }
        });
        Page<Clazz> page = (Page<Clazz>) clazzList;
        PageBean pageBean = new PageBean(page.getTotal(), page.getResult());
        return pageBean;
    }

    @Override
    public void delete(Integer id) {
        Integer count = studentMapper.countByClazzId(id);
        if (count>0){
            throw new BuinessException("该班级下有学生，不能删除");
        }
        clazzMapper.delete(id);
    }

    @Override
    public void add(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.add(clazz);
    }

    @Override
    public Clazz findById(Integer id) {
        return clazzMapper.findById(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public List<Clazz> findClazz() {
        return clazzMapper.findClazz();
    }
}
